package com.example.lanouhn.firstapp.activity.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.activity.BrokerDealerActivity;
import com.example.lanouhn.firstapp.activity.activity.GoodsDetailsActivity;
import com.example.lanouhn.firstapp.activity.adapter.GoodsRecommendAdapter;
import com.example.lanouhn.firstapp.activity.model.Goods;
import com.example.lanouhn.firstapp.activity.model.GoodsImage;
import com.example.lanouhn.firstapp.activity.model.Syomb;
import com.example.lanouhn.firstapp.activity.utils.DialogUtil;
import com.example.lanouhn.firstapp.activity.utils.GoodsDataJson;
import com.example.lanouhn.firstapp.activity.utils.GoodsImageJson;
import com.example.lanouhn.firstapp.activity.utils.GoodsRecommendJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.utils.SPUtils;
import com.example.lanouhn.firstapp.activity.utils.SyombJson;
import com.example.lanouhn.firstapp.activity.utils.T;
import com.example.lanouhn.firstapp.activity.view.ad.SlideShowView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 商品页
 */
public class IntoGoodsGoodsFragment extends Fragment {
    //接收上一个解析传递过来的id值  用来拼接网络地址
    private String goods_id;

    //推荐商品列表
    private RecyclerView recyclerView;
    //定义数组
    private List<Goods> dataList;

    private Goods dList;//商品详情中间数据
    private GoodsImage iList;//轮播图的数据
    //加载进度
    private ProgressBar progressBar;
    //适配器
    private GoodsRecommendAdapter adapter;

    //弹出标题栏
    private LinearLayout ll_jumpText;
    private ImageView openText;//点击图片
    private boolean isVisibil = true;//判断值
    //解析文本
    private TextView goods_name;
    private TextView goods_price;
    private TextView goods_salenum;
    private TextView mobile_body;
    private TextView goods_storage;
    private TextView goods_promotion_price;
    private SlideShowView slideShowView;


    //进入店铺跳转商城页面
    private TextView enterShop;
    //店内搜索跳转商城页面
    private TextView storeSearch;

    //拨号
    private ImageView phone;

    private boolean isCheck = false;
    //立即购买，加入购物车  点击加减商品数量
    private Button addToCart;
    private Button buyNow;
    private TextView btn_reduce;
    private TextView btn_add;
    private EditText et_num;
    private String key;
    private Syomb slist;

    //动态注册广播接收器的变量类型
    private MyBroadcastReceiver myBroadcastReceiver;




    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_into_goods_goods_fragment, null);

        phone = (ImageView) view.findViewById(R.id.phone);
        enterShop = (TextView) view.findViewById(R.id.enterShop);
        storeSearch = (TextView) view.findViewById(R.id.storeSearch);

        //得到Activity中传递过来的id值
        goods_id = getActivity().getIntent().getStringExtra("str");
        key = (String) SPUtils.get(getActivity(),"log_key","");
        //找控件
        initView( view);

        //  绑定数据
        initData();
        //点击事件
        setOnclickListener();

        //动态注册广播接收器
        myBroadcastReceiver = new MyBroadcastReceiver();
        //过滤器
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("into_car");
        //注册
        getActivity().registerReceiver(myBroadcastReceiver, mFilter);


        return view;

    }

    private void setOnclickListener() {

        //中间商家信息的点击弹出框  点击事件
        openText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isVisibil && !isCheck) {
                    ll_jumpText.setVisibility(View.VISIBLE);
                    openText.setImageResource(R.mipmap.chevron_down);
                } else {
                    ll_jumpText.setVisibility(View.GONE);
                    openText.setImageResource(R.mipmap.chevron_up);
                }
                isVisibil =!isVisibil;
                isCheck = !isCheck;
            }
        });



       // 进入店铺点击事件
        enterShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), BrokerDealerActivity.class);
                startActivity(intent);
            }
        });

        //店内搜索点击事件
        storeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), BrokerDealerActivity.class);
                startActivity(intent);
            }
        });

        //拨号点击事件
        phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ "020-87781618"));
                startActivity(intent);
            }
        });


        //点击数量加一
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            int num = Integer.parseInt(String.valueOf(et_num.getText()));
                    num ++;
                    et_num.setText(num+"");
            }
        });
        //点击数量减一
        btn_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int num = Integer.parseInt(String.valueOf(et_num.getText()));
                if(num>1){
                num --;
                et_num.setText(num+"");
                }else{
                    T.showShort(getActivity(),"购买数量不能少于1件");
                    et_num.setText(1+"");
                }
            }
        });
        //点击加入购物车
        addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //点击加入购物车的post请求url
                        String url = "http://www.niaolema.com/mobile/index.php?act=member_cart&op=cart_add";
                        String params ="key="+key+"&goods_id="+goods_id+"&quantity="+et_num.getText();
                        String result = HttpUtils.doPost(url, params);
                        slist = SyombJson.getSyomb(result);



                        if (slist.getCode()==200 && slist.getDatas()==1){
                            handler.sendEmptyMessage(1);
                        }else {
                            handler.sendEmptyMessage(0);
                        }
                    }
                }).start();
            }
            private Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);

                    switch (msg.what) {
                        case 0:
                            T.showShort(getActivity(),"加入失败，请重试");
                            break;
                        case 1:
                            DialogUtil.showDialog2(getActivity(), "加入购物车成功", false);

                            Intent intent =new Intent();
                            intent.setAction("aaaaa");
                            getActivity().sendBroadcast(intent);


                            break;
                    }
                }
            };
        });
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //请求网络数据
        getDataFromWeb();

    }

    /**
     * 请求网路数据，开启新线程
     */
    private void getDataFromWeb() {
//显示进度条
        progressBar.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {

                //Request是OkHttp中访问的请求，Builder是辅助类。Response即OkHttp中的响应。
                //使用引包的OKHttp方法来进行网络请求操作
                OkHttpClient okHttpClient = new OkHttpClient();
                //request请求
                Request request = new Request.Builder()
                        .url(getRequestUrl())
                        .build();

                Call call = okHttpClient.newCall(request);

                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String result = response.body().string();


                        //将获取到的Json数据解析,通过封装的工具类
                        dataList = GoodsRecommendJson.getGoodsRecommend(result);
                        //中间商品信息的数据
                        dList = GoodsDataJson.getData(result);
                        //轮播图的数据
                        iList = GoodsImageJson.getImage(result);

                        //判断解析出的集合长度,有数据就显示,无数据就不显示
                        if ((dataList.toString().length() > 0) || dList.toString().length() > 0)
                            handler.sendEmptyMessage(1);
                    }
                });
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //取消loading  进度条
            progressBar.setVisibility(View.GONE);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(),
                            "请求失败,请稍候再试!!!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
//                    获取数据成功,并解析数据成功,创建adapter
                    adapter = new GoodsRecommendAdapter(dataList, getActivity());
                    //设置adapter
                    recyclerView.setAdapter(adapter);

                    //recyclerview的item的点击事件
                    adapter.setGoodsRecommendRecyviewListent(new GoodsRecommendAdapter.GoodsRecommendRecyclerViewListener(){
                        @Override
                        public void onclick(View view, int postion) {
                            //跳转到商品详情页面  并且将推荐商品的id传递过去
                            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                            intent.putExtra("goods_id", dataList.get(postion).getGoods_id());
                            startActivity(intent);
                        }
                    });
                    //执行完毕，更新UI,
                    adapter.notifyDataSetChanged();
                    goods_name.setText(dList.getGoods_name());
                    goods_price.setText(dList.getGoods_price());
                    goods_salenum.setText(dList.getGoods_salenum());
                    if (dList.getMobile_body().isEmpty()){
                        mobile_body.setText("");
                    }else{
                        mobile_body.setText(Html.fromHtml(dList.getMobile_body()));
                    }
                    goods_storage.setText(dList.getGoods_storage());
                    goods_promotion_price.setText(dList.getGoods_promotion_price());
                    //中划线
                    goods_promotion_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                    //轮播图
                    List<String> urls = new ArrayList<>();
                    //将分割的网址片段  放到集合中
                    String[] imageUrls = iList.getGoods_image().split(",");
                    //循环取出每个图片的网址
                    for (int i = 0; i < imageUrls.length; i++) {
                        urls.add(imageUrls[i]);
                    }
                    //调用轮播图类里面的方法   传入图片数据到其中的构造器
                    slideShowView.initData(urls);
                    break;
            }
        }
    };
    /**
     * 绑定控件
     */
    private void initData() {
        //加载布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        //设置图片距离 首页的最新商品列表
        SpacesItemDecoration decoration = new SpacesItemDecoration(9);
        recyclerView.addItemDecoration(decoration);
    }
    //设置图片距离
    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = space;
            }
        }
    }
    /**
     * 找控件的集合
     * @param view
     */
    private void initView(View view) {
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        slideShowView = (SlideShowView) view.findViewById(R.id.slideShowView);
        //弹出文本框设置
        ll_jumpText = (LinearLayout) view.findViewById(R.id.ll_jumpText);
        openText = (ImageView) view.findViewById(R.id.openText);
        //解析文本控件
        goods_name = (TextView) view.findViewById(R.id.goods_name);
        goods_price = (TextView) view.findViewById(R.id.goods_price);
        goods_salenum = (TextView) view.findViewById(R.id.goods_salenum);
        mobile_body = (TextView) view.findViewById(R.id.mobile_body);
        goods_storage = (TextView) view.findViewById(R.id.goods_storage);
        goods_promotion_price = (TextView) view.findViewById(R.id.goods_promotion_price);

        //
        addToCart = (Button) view.findViewById(R.id.addToCart);
        buyNow = (Button) view.findViewById(R.id.buyNow);
        btn_reduce = (TextView) view.findViewById(R.id.btn_reduce);
        btn_add = (TextView) view.findViewById(R.id.btn_add);
        et_num = (EditText) view.findViewById(R.id.et_num);
    }
    /**
     * 拼接网络地址  并将其返回
     *
     * @return
     */
    private String getRequestUrl() {
        return "http://www.niaolema.com/mobile/index.php?act=goods&op=goods_detail&goods_id=" + goods_id;
    }

//创建内部类事件广播接收器事件
    private class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //启动点击事件
        new Thread(new Runnable() {
            @Override
            public void run() {
                //点击加入购物车的post请求url
                String url = "http://www.niaolema.com/mobile/index.php?act=member_cart&op=cart_add";
                String params ="key="+key+"&goods_id="+goods_id+"&quantity="+et_num.getText();
                String result = HttpUtils.doPost(url, params);
                slist = SyombJson.getSyomb(result);



                if (slist.getCode()==200 && slist.getDatas()==1){
                    handler.sendEmptyMessage(1);
                }else {
                    handler.sendEmptyMessage(0);
                }
            }
        }).start();

    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    T.showShort(getActivity(),"加入失败，请重试");
                    break;
                case 1:
                    DialogUtil.showDialog2(getActivity(), "加入购物车成功", false);

                    Intent intent =new Intent();
                    intent.setAction("aaaaa");
                    getActivity().sendBroadcast(intent);


                    break;
            }
        }
    };
}
    @Override
    public void onDestroy() {
        super.onDestroy();

        getActivity().unregisterReceiver(myBroadcastReceiver);
    }
}
